<?php
/*

Version 0.1
SEMF - Web Desiging Framework for Sport Event Managment
Copyright (C) 2006, SEMF Developers

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/
error_reporting(0);
if(file_exists('../../conf/semf.xml')){
	 header("Location: http://" . $_SERVER['HTTP_HOST']
        . dirname(dirname(dirname(($_SERVER['PHP_SELF'])))). "/" .'index.php');
}

if(!file_exists('../../conf') || !is_writable('../../conf')) {
    $conf_path = realpath('../../'). "/conf";
    die("Please make sure the conf ('$conf_path') directory exists and is writable to the apache server");
    return;
}

if(!file_exists('../../projects') || !is_writable('../../projects')) {
    $projects_path = realpath('../../'). "/projects";
    die("Please make sure the projects ('$projects_path') directory exists and is writable to the apache server");
    return;
}

$title = $_GET["title"];
if(!isset($title))
{
    $title = "SEMF Installation";
}

function install($project_name, $project_dir, $project_database, $admin_name, $admin_password,$mysql_server, $mysql_user,$mysql_password, $semf_root)
{
    // create the database..
    $link = mysql_connect($mysql_server, $mysql_user, $mysql_password);
    if($link)
    {
        $db_selected = mysql_select_db($project_database, $link);
        if ($db_selected) {
            $tmp_result = mysql_query("SHOW tables;",$link);
            if($tmp_result){
                $row = mysql_fetch_array($tmp_result);
            }else {
                return  "<font color='#FF0000'>". mysql_error()."\n"."</font>";
            }

            if($row){
                return  "<font color='#FF0000'>".
                'Database '.$project_database.' is not empty' . mysql_error()."\n".
                "</font>";
            }

        }
        else if(!mysql_query("CREATE DATABASE ".$project_database))
        {
            return  "<font color='#FF0000'>".
            'Error creating database '.$project_database.': ' . mysql_error()."\n".
            "</font>";
        }

        // here we are copying the sample1 directory to the project dir
        if (is_dir($semf_root."projects/sample1")) {
            recurse_copy($semf_root."projects/sample1", $semf_root.$project_dir);
        }
        else {
            if(!is_dir($semf_root.$project_dir))
            {
                mkdir($semf_root.$project_dir);
            }
            

            $sys_dir = $semf_root.$project_dir."/"."System/";
            
            if(is_dir($sys_dir) || is_file($sys_dir))
            {
                return "<font color='#FF0000'>Project System Directory already exists!</font>";
            }
            mkdir($sys_dir);
            
            copy("../xmls/module.xml", $sys_dir."module.xml");
        }
        recurse_copy($semf_root."/store", $semf_root.$project_dir. "/store");
        
        $semf_xml = $semf_root."conf/semf.xml";

        $project_xml = $semf_root.$project_dir."/"."project.xml";

        $doc = new DOMDocument();
        $root = NULL;
        if (file_exists($semf_xml))
        {
            $doc->load($semf_xml);
            $root = $doc->documentElement;
        }
        else
        {
            $root = $doc->createElement('semf');
            $doc-> appendChild($root);
        }

        $project_element = $doc->createElement('project');
        $project_element->setAttribute('name', $project_name);
        $root->appendChild($project_element);

        $path_element = $doc->createElement('dir');
        $path_text = $doc->createTextNode($project_dir);
        $path_element-> appendChild($path_text);
        $project_element-> appendChild($path_element);

        $doc->save($semf_xml);

        $doc = new DOMDocument();

        $project_element = $doc->createElement('project');
        $project_element->setAttribute('name', $project_name);
        $doc-> appendChild($project_element);

        $database_element = $doc->createElement('database');
        $database_element->setAttribute('name', $project_database);
        $project_element-> appendChild($database_element);

        $password_element = $doc->createElement('password');
        $password_text = $doc->createTextNode($mysql_password);
        $password_element->appendChild($password_text);
        $database_element->appendChild($password_element);

        $server_element = $doc->createElement('server');
        $server_text = $doc->createTextNode($mysql_server);
        $server_element->appendChild($server_text);
        $database_element->appendChild($server_element);

        $doc->save($project_xml);

        //we are not saving administrator details in the xml, rather they would be put in db..
        $dont_echo = 1;
        $req_module_name = "System";
        $project_home = $project_dir."/";

        include_once("../lib/schema_generator.php");

        //reconnect the information
        $link = mysql_connect($mysql_server, 'root', $mysql_password);
        if(!$link)
        {
            return "Error in query: $query ".mysql_error();
        }

        if(!mysql_select_db($project_database))
        {
            return "Error in query: $query ".mysql_error();
        }

        //insert the new entry
        $query = "INSERT INTO System_Administrator (__newly_created, name, password)".
        " values (true, '".$admin_name."', MD5('".$admin_password."'))";
        $result = mysql_query($query);
        if(!$result) //should return the error..
        {
            return "Error in query: $query ".mysql_error();
        }

        //we are done with the database..
        mysql_close($link);

        //copy the xmls into System directory..

        //echo "dir exists: ".$semf_root.$project_dir;

    }
    else
    {
        return  "<font color='#FF0000'>Could not connect to the database..</font>";
    }

    return false;
}

function recurse_copy($src,$dst) {
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            if ( is_dir($src . '/' . $file) ) {
                recurse_copy($src . '/' . $file,$dst . '/' . $file);
            }
            else {
                copy($src . '/' . $file,$dst . '/' . $file);
            }
        }
    }
    closedir($dir);
} 

if(isset($_POST['project_name'])){
    $project_name = $_POST["project_name"];
    $project_dir = $_POST["project_dir"];
    $project_database = $_POST["project_database"];
    $admin_name = $_POST["admin_name"];
    $admin_password = $_POST["admin_password"];

    $mysql_server = $_POST["mysql_server"];
    $mysql_password = $_POST["mysql_password"];
    $mysql_user = $_POST['mysql_user'];


    $semf_root = "../../";

    $target_file = $semf_root."index.php";

    $message = "";
    if(substr($project_dir, -1) != "/")
    {
        $project_dir = $project_dir."/";
    }

    if(!isset($project_name) || $project_name == "")
    {
        $message .= "<font color='#FF0000'>Project Name Cannot be empty</font>";
    }
    //contineue checking for error.
    elseif(!isset($project_dir) || $project_dir == "")
    {
        $message .= "<font color='#FF0000'>Project Directory Cannot be empty</font>";
    }
    else
    {
        //installation steps..
        $val = install($project_name, $project_dir, $project_database, $admin_name,
        $admin_password, $mysql_server,$mysql_user, $mysql_password, $semf_root);
        $message.=$val;
        if($val == false){
            $success="Installation is completed. Thank you for choosing SEMF. ".
            "Click Next to Continue to the project.";
        }
    }
    if(isset($success) && !empty($success)){
        header("Location: http://" . $_SERVER['HTTP_HOST']
        . dirname($_SERVER['PHP_SELF'])
        . "/" .'complete.php?msg='.$success.'&target_file='.$target_file);
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-2" />
<title><?php echo $title?></title>
<script language="javascript">
SEMF = {};
SEMF.projectDirPanel = null;

SEMF.init = function()
{
    SEMF.projectDirPanel = new YAHOO.widget.Panel("projectDirPanel",  {
        effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25},

        width:"550px", height:"380px",
        underlay:"shadow",   fixedcenter: true,
        close:true, visible:false, draggable:true, modal:true }
        );
        SEMF.projectDirPanel.render();
}

SEMF.showDirWindow = function()
{
    if(SEMF.projectDirPanel)
    {
        SEMF.currentPanel = SEMF.projectDirPanel;
        SEMF.projectDirPanel.show();
    }
}

SEMF.selectDirectory = function(dirName)
{
    var projectDir = document.getElementById('projectDir');
    projectDir.value = dirName;
}

SEMF.submitPage = function()
{
    document.forms[0].submit();
}

SEMF.onChangeProject = function(ctrl)
{
    var projectName = ctrl.value;
    var projectDir = document.getElementById('projectDir');

    var dbName = document.getElementById('dbName');

    projectDir.value = "projects/"+projectName;
    dbName.value = projectName;
}

</script>

<script language="javascript" src="../../yui/yahoo.js"></script>
<script language="javascript" src="../../yui/dom.js"></script>
<script language="javascript" src="../../yui/animation.js"></script>
<script language="javascript" src="../../yui/event.js"></script>
<script language="javascript" src="../../yui/dragdrop.js"></script>
<script language="javascript" src="../../yui/container.js"></script>

<link rel="stylesheet" href="images/style.css" type="text/css" />
<link rel="stylesheet" href="../../styles/container.css"  type="text/css" />
<link rel="shortcut icon" href="../../icons/semf.ico" />
</head>
<body>
	<div class="content">
		<div class="header">
		  <div class="logo">
				<h1>SEMF Installer  </h1>
			</div>
		</div>
		
		<div class="subheader">
		</div>
		<div>
		<?php echo $message ?>
		</div>
		<div class="left">
			<div class="left_articles">
				<h2>Project Information </h2>
		  </div>
			<form method="post" action="install.php">
			<div class="left_links">
			<table border="0">
			<tr>
			<p>
			<td>Project Name : </td>
			<td>
			<input onchange="SEMF.onChangeProject(this)" type="text" name="project_name" value=""  class="login" />
		</td>
			</p>
			</tr>
			<tr>
			<p>
			<td>Project Dir : </td>
			<td><input id="projectDir" type="text" name="project_dir" value=""  class="login" />
      <img style="cursor:pointer" onclick="SEMF.showDirWindow()"
		 src="../../page_designer/images/properties/window-new.png" /></td>
			</p>
			</tr>	
			</table>
		  </div>
		  <div class="left_articles">
				<h2>Administrator Information </h2>
		  </div>
			<div class="left_links">
			<table border="0">
			<tr>
			<p>
			<td>Name : </td>
			<td><input type="text" name="admin_name" class="login" /></td>
			</p>
			</tr>
			<tr>
			<p>
			<td>Password : </td>
			<td><input type="password" name="admin_password" class="login"  /></td>
			</p>
			</tr>	
			</table>
		  </div>
		  <div class="left_articles">
				<h2>My SQL Configuration </h2>
		  </div>
			<div class="left_links">
			<table border="0">
			<tr>
			<p>
			<td> Host  : </td>
			<td><input type="text" name="mysql_server" value="localhost" class="login" /></td>
			</p>
			</tr>
			<tr>
			<p>
			<td>Username : </td>
			<td><input type="text" name="mysql_user" class="login" /></td>
			</p>
			</tr>	
			<tr>
			<p>
			<td>Password : </td>
			<td><input type="password" name="mysql_password"  class="login" /></td>
			</p>
			</tr>
			<tr>
			<p>
			<td>Database : </td>
			<td><input id="dbName" type="text" name="project_database" value="" class="login" /></td>
			</p>
			</tr>
			</table>
		  </div>
		 <input type="hidden" name="title" value="<?php echo $title?>" />
		 </form>
			<div class="left_box">
				<p align="right"><a href="javascript:SEMF.submitPage();">Next</a> </p>
				
		  </div>
		</div>	
		<div class="footer">
		  <p>&copy; Copyright 2007 SEMF Developers <a href="http://www.solucija.com/" title="What's your solution?"></a></p>
	  </div>
	</div>
	
	<div id="projectDirPanel" style="visibility:visible">
<div id="projectDirPanelHeader" class="hd">Find Project Directory</div>
<div id="projectDirPanelView" class="bd" style="width:98% position:absolute;" >
	<iframe id="projectDirPanelFrame" style="border:none;width:100%; height:340px; overflow:auto" src="../lib/dir_list.php?dir_root=projects&dir_root_path=./&dirs_only=1">
	</iframe>
</div>
<div id="projectDirPanelFooter" class="ft"></div>
</div>

<script>
SEMF.init();
</script>
</body>
</html>
